from Pacx import *
from Rsyncer import *
from Util import *
import getopt
import sys
import traceback
import subprocess
import MySQLdb

class FileCleaner(Pacx):
    
    def __init__(self):
        Pacx.__init__(self)
        self.extractiondir = self.config.get("extraction", "outputdir")
    
    def clean(self):
        query = "select id,package from PACKAGES P where not exists (select pid from REPOSITORY_PACKAGES RP where islatest=1 and pid=id) order by package"
        
        cursor = self.db.cursor()
        out = cursor.execute(query)
        rows = cursor.fetchall()
        for row in rows:
            hash = str(string_to_integer(row[1]))
            path = os.path.join(self.extractiondir, hash, row[1])
            if (os.path.exists(path)):
                print "Deleting %s ..." % path
            try:
                shutil.rmtree(path, True, None)
            except Exception, e:
                print "Error: %s " % str(e)
            
        cursor.close()
        
        
def main():
    cleaner = FileCleaner()
    cleaner.clean()
    cleaner.db.close()


if __name__ == "__main__":
    main()
